﻿using CinemaMaestro.BusinessLayer.Contracts;
using CinemaMaestro.Common.IocContainer;
using CinemaMaestro.DataLayer.Contracts.Entities;
using CinemaMaestro.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace CinemaMaestro.RestApi.Controllers
{
    [Authorize]
    public class MoviesController : ApiController
    {

        [HttpGet]
        public IHttpActionResult GetAllMovies()
        {
            var businessUoW = Resolver.Get<IBusinessObjectFactory>();

            var list = businessUoW.Movies.Read().ToList();

            List<MovieViewModel> models = new List<MovieViewModel>();

            foreach (var model in list)
            {
                MovieViewModel movie = model;
                models.Add(movie);
            }

            return Ok(models);
        }

        [HttpGet]
        public IHttpActionResult GetMovie(int id)
        {
            var businessUoW = Resolver.Get<IBusinessObjectFactory>();

            var movie = businessUoW.Movies.Read().FirstOrDefault(x => x.Id == id);
            if (movie == null)
            {
                return NotFound();
            }
            MovieViewModel movieVM = movie;
            return Ok(movieVM);
        }

        [HttpPut]
        public IHttpActionResult UpdateMovie(MovieViewModel movieVM)
        {
            var businessUoW = Resolver.Get<IBusinessObjectFactory>();
            Movie movie = movieVM;
            businessUoW.Movies.Update(movie);
            return Ok();
        }

        [HttpDelete]
        public IHttpActionResult DeleteMovie(int id)
        {
            var businessUow = Resolver.Get<IBusinessObjectFactory>();
            var hasDependencies = businessUow.Screenings.ScreeningHasRelationWithMovie(id);
            if (hasDependencies)
            {
                return NotFound();
            }
            var deleted = businessUow.Movies.Delete(id);
            if (deleted)
            {
                return Ok();
            }
            return NotFound();
        }

        [HttpPost]
        public IHttpActionResult CreateMovie(MovieViewModel movieVM)
        {
            var businessUoW = Resolver.Get<IBusinessObjectFactory>();
            Movie movie = movieVM;
            businessUoW.Movies.Create(movie);
            return Ok();
        }

    }
}
